package models

import "gorm.io/gorm"

// 房源表
type House struct {
	gorm.Model
	UserId  int     `gorm:"type:int;not null;comment:用户id"`
	City    string  `gorm:"type:varchar(30);not null;comment:城市"`
	Address string  `gorm:"type:varchar(256);comment:小区地址"`
	Floor   string  `gorm:"type:varchar(20);comment:楼层"`
	Size    float64 `gorm:"type:decimal(10,2);comment:房屋面积"`
	Price   int     `gorm:"type:int;comment:月租金"`
	Info    string  `gorm:"type:varchar(256);comment:房源描述"`
	Status  int     `gorm:"type:int;default:0;comment:房源状态(0-待上架,1-已上架,2-已出租)"`
}

// 房源图片表
type HouseImage struct {
	gorm.Model
	HouseId int    `gorm:"type:int;comment:房源id"`
	Image   string `gorm:"type:varchar(256);comment:房源图片"`
	Title   string `gorm:"type:varchar(20);comment:标题"`
}

// 发布房源
func (h *House) Create() error {
	return DB.Create(&h).Error
}

// 发布房源图片
func (hs *HouseImage) Creates() error {
	return DB.Create(&hs).Error
}

// 查询房源
func (h *House) Find(id int) error {
	return DB.Where("id = ?", id).Find(&h).Error
}

func (h *House) Update(houseId, Status int) error {
	return DB.Model(&h).Where("houses_id = ?", houseId).Update("house_status", Status).Error
}

// 个人房源列表
func (h *House) FindHouse(status, Page, size int) (List []House) {
	page := Page
	if page <= 0 {
		page = 1
	}

	pageSize := size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	if status != 0 {
		DB.Where("status = ?", status).Offset(offset).Find(&List)
	}
	DB.Offset(offset).Find(&List)
	return
}

// 管理房源列表
func (h *House) FindHouses() (List []House) {
	DB.Find(&List)
	return
}
